package com.watereast;

import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AesDesUtils {
    private static final Logger log = LoggerFactory.getLogger(AesDesUtils.class);

    public static final String DEFAULT_WORLD = "policycheck2019";

    private static final String KEY_ALGORITHM = "AES";

    private static final String CHARSET = "UTF-8";

    public static final String SXWX_UNDER_WRITING = "sxwx2kjgx";

    public static final String SXWX_UNDER_WRITING_EMP = "sxwx2bdgj";

    public static final String KJGX_DING_DONG_NOTICE = "newtouchnewtouch";

    public static final String PLANBOOK_WORLD = "GapToPlanBook320";

    public static final String KEJIGEXIAN_ANALYSE_KEY = "keJiAnalyseKey001";

    public static String encrypt(String uncryptedStr, String secretKey) {
        try {
            if (StringUtils.isEmpty(uncryptedStr))
                return null;
            Cipher cipher = Cipher.getInstance("AES");
            byte[] byteContent = uncryptedStr.getBytes("UTF-8");
            cipher.init(1, getSecretKey(secretKey));
            byte[] result = cipher.doFinal(byteContent);
            return parseByte2HexStr(result);
        } catch (Exception ex) {
            log.error("aes, ex);
            return null;
        }
    }

    private static SecretKeySpec getSecretKey(String pwd) {
        if (StringUtils.isEmpty(pwd))
            pwd = "policycheck2019";
        KeyGenerator kgen = null;
        try {
            kgen = KeyGenerator.getInstance("AES");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(pwd.getBytes());
            kgen.init(128, random);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
            return keySpec;
        } catch (Exception ex) {
            log.error(", ex);
            return null;
        }
    }

    public static String parseByte2HexStr(byte[] buf) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1)
                hex = '0' + hex;
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    public static String bytes2HexString(byte[] b) {
        if (null == b)
            return null;
        String ret = "";
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1)
                hex = '0' + hex;
            ret = ret + hex.toUpperCase();
        }
        return ret;
    }
}
